package com.jie.other.jetpack

import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.blankj.utilcode.util.LogUtils
import com.jie.commonlib.base.BaseActivity
import com.jie.other.R
import com.jie.other.databinding.OtherActivityViewModelBinding
import com.jie.other.jetpack.viewmodel.UserViewModel

/**
 * ViewModel框架学习测试页面
 */
class ViewModelActivity : BaseActivity() {

    private lateinit var mViewBinding : OtherActivityViewModelBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mViewBinding = OtherActivityViewModelBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
        initActionBar()
        val userViewModel by viewModels<UserViewModel>()

        userViewModel.getLoading().observe(this) {
            mViewBinding.pbLoading.visibility = if (it) {
                View.VISIBLE
            } else {
                View.GONE
            }
        }
        userViewModel.getRequestResult().observe(this) {
            if (it.code == 0) {
                mViewBinding.tvError.visibility = View.GONE
                mViewBinding.flList.visibility = View.VISIBLE
                mViewBinding.flDetail.visibility = View.VISIBLE
                supportFragmentManager.beginTransaction()
                    .replace(R.id.fl_list, ViewModelListFragment())
                    .commit()
                supportFragmentManager.beginTransaction()
                    .replace(R.id.fl_detail, ViewModelDetailFragment())
                    .commit()
            } else {
                mViewBinding.tvError.apply {
                    visibility = View.VISIBLE
                    text = it.message
                }
            }
        }
        userViewModel.getBtnVisible().observe(this) {
            mViewBinding.btnGet.visibility = if (it) {
                View.VISIBLE
            } else {
                View.GONE
            }
            mViewBinding.tvError.visibility = if (it && (userViewModel.getRequestResult().value
                    ?: 0) != 0
            ) {
                View.VISIBLE
            } else {
                View.GONE
            }
        }
        userViewModel.getUserList().observe(this) {
            LogUtils.i("user list is change")
        }

        mViewBinding.btnGet.setOnClickListener {
            userViewModel.loadUserList()
        }

    }

    private fun initActionBar() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setTitle(R.string.other_view_model)
    }

}